#include <stdio.h>
#include <string.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>

int sm3_hmac(const unsigned char *key, size_t key_len,
             const unsigned char *data, size_t data_len,
             unsigned char *out) {
    const EVP_MD *md = EVP_sm3();
    if (!md) return -1;
    if (!HMAC(md, key, key_len, data, data_len, out, NULL))
        return -1;
    return 0;
}

int main() {
    // 示例密钥和数据
    const unsigned char key[] = "123456";
    const unsigned char data[] = "20231318fsl";
    size_t key_len = strlen((const char *)key);
    size_t data_len = strlen((const char *)data);

    // SM3 输出长度为 32 字节
    unsigned char out[EVP_MAX_MD_SIZE];
    int out_len = 32;  // SM3 digest length

    if (sm3_hmac(key, key_len, data, data_len, out) != 0) {
        fprintf(stderr, "SM3-HMAC calculation failed.\n");
        return 1;
    }

    // 打印十六进制结果
    printf("SM3-HMAC: ");
    for (int i = 0; i < out_len; i++) {
        printf("%02x", out[i]);
    }
    printf("\n");

    return 0;
}
